<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { showToast } from 'vant'
import { useUserStore } from '@/stores'
import {
  getMessageList,
  getUnreadMessageCount,
  markMessagesAsRead,
  clearAllUnreadMessages
} from '@/services/consult'
import type { MessageListItem, MessageListResponse } from '@/types/user'

const userStore = useUserStore()
const messageList = ref<MessageListItem[]>([])
const loading = ref(false)
const loadingMore = ref(false)
const unreadCount = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const hasMore = ref(true)
const sortByUnread = ref(true)

// 获取消息列表
const loadMessageList = async (isRefresh = false) => {
  if (!userStore.user?.id) return

  // 如果是刷新，重置分页参数
  if (isRefresh) {
    currentPage.value = 1
    hasMore.value = true
    messageList.value = []
  }

  if (loading.value || loadingMore.value || !hasMore.value) return

  try {
    if (isRefresh) {
      loading.value = true
    } else {
      loadingMore.value = true
    }

    console.log('获取消息列表:', {
      userId: userStore.user.id,
      page: currentPage.value,
      size: pageSize.value,
      sortByUnread: sortByUnread.value
    })

    const res = await getMessageList(
      userStore.user.id,
      currentPage.value,
      pageSize.value,
      sortByUnread.value
    )

    console.log('消息列表响应:', res)

    if (res.data) {
      const responseData = res.data as MessageListResponse

      if (isRefresh) {
        messageList.value = responseData.list
      } else {
        messageList.value.push(...responseData.list)
      }

      hasMore.value = responseData.hasMore
      currentPage.value = responseData.page

      console.log('更新后的消息列表:', messageList.value)
      console.log('是否还有更多:', hasMore.value)
    }
  } catch (error) {
    console.error('获取消息列表失败:', error)
    showToast('获取消息列表失败')
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

// 加载更多消息
const loadMore = async () => {
  if (!hasMore.value || loadingMore.value) return

  currentPage.value += 1
  await loadMessageList(false)
}

// 获取未读消息数量
const loadUnreadCount = async () => {
  if (!userStore.user?.id) return

  try {
    const res = await getUnreadMessageCount(userStore.user.id)
    unreadCount.value = res.data
  } catch (error) {
    console.error('获取未读消息数量失败:', error)
  }
}

// 标记消息为已读
const markAsRead = async (consultId: string) => {
  if (!userStore.user?.id) return

  try {
    await markMessagesAsRead(consultId, userStore.user.id)
    // 重新加载消息列表
    loadMessageList(true)
    loadUnreadCount()
  } catch (error) {
    console.error('标记已读失败:', error)
  }
}

// 进入聊天室
const enterChat = (item: MessageListItem) => {
  // 如果有未读消息，先标记为已读
  if (item.unreadCount > 0) {
    markAsRead(item.consultId)
  }
  // 跳转到聊天室
  window.location.href = `/room?orderId=${item.consultId}`
}

// 清除所有未读消息
const clearAllUnread = async () => {
  if (!userStore.user?.id) return

  try {
    await clearAllUnreadMessages(userStore.user.id)
    // 重新加载数据
    loadMessageList(true)
    loadUnreadCount()
    showToast('已全部标记为已读')
  } catch (error) {
    console.error('清除未读失败:', error)
    showToast('操作失败')
  }
}

// 切换排序方式
const toggleSort = () => {
  sortByUnread.value = !sortByUnread.value
  loadMessageList(true)
}

// 格式化时间
const formatTime = (timeStr: string) => {
  const time = new Date(timeStr)
  const now = new Date()
  const diff = now.getTime() - time.getTime()

  if (diff < 60 * 1000) {
    return '刚刚'
  } else if (diff < 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 1000))}分钟前`
  } else if (diff < 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 60 * 1000))}小时前`
  } else {
    return time.toLocaleDateString()
  }
}

// 获取头像 URL
const getAvatarUrl = (avatar: string | null) => {
  if (!avatar) return '/default-avatar.png'
  if (avatar.startsWith('http')) return avatar
  const baseUrl =
    import.meta.env.VITE_APP_API_BASE_URL || 'http://localhost:8080'
  return `${baseUrl}/public/images/${avatar}`
}

onMounted(() => {
  loadMessageList(true)
  loadUnreadCount()
})
</script>

<template>
  <div class="notify-page">
    <cp-nav-bar title="消息通知">
      <template #right>
        <div class="nav-actions">
          <div class="sort-btn" @click="toggleSort">
            <van-icon :name="sortByUnread ? 'sort-desc' : 'sort-asc'" />
            {{ sortByUnread ? '未读优先' : '时间排序' }}
          </div>
          <div class="clear-btn" @click="clearAllUnread" v-if="unreadCount > 0">
            <van-icon name="delete-o" />
            清除未读
          </div>
        </div>
      </template>
    </cp-nav-bar>

    <div class="message-header" v-if="unreadCount > 0">
      <van-notice-bar
        :text="`您有 ${unreadCount} 条未读消息`"
        color="#1989fa"
        background="#ecf9ff"
        left-icon="volume-o"
      />
    </div>

    <van-pull-refresh v-model="loading" @refresh="() => loadMessageList(true)">
      <van-list
        v-model:loading="loadingMore"
        :finished="!hasMore"
        finished-text="没有更多了"
        @load="loadMore"
      >
        <div class="message-list">
          <div
            v-for="item in messageList"
            :key="item.consultId"
            class="message-item"
            @click="enterChat(item)"
          >
            <div class="avatar">
              <van-image
                :src="getAvatarUrl(item.otherUserAvatar)"
                round
                width="50"
                height="50"
              />
              <van-badge
                v-if="item.unreadCount > 0"
                :content="item.unreadCount > 99 ? '99+' : item.unreadCount"
                class="unread-badge"
              />
            </div>

            <div class="message-content">
              <div class="message-header">
                <div class="name">{{ item.otherUserName }}</div>
                <div class="time">{{ formatTime(item.lastMessageTime) }}</div>
              </div>
              <div class="message-preview">
                {{ item.lastMessage || '暂无消息' }}
              </div>
              <div class="status">{{ item.consultStatus }}</div>
            </div>

            <van-icon name="arrow" class="arrow" />
          </div>

          <div v-if="messageList.length === 0 && !loading" class="empty">
            <van-empty description="暂无消息" />
          </div>
        </div>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<style lang="scss" scoped>
.notify-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-top: 46px; /* 为导航栏留出空间，避免遮挡 */
}

.nav-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.sort-btn,
.clear-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: #969799;
  padding: 4px;
  cursor: pointer;
  transition: color 0.2s;

  &:hover {
    color: #1989fa;
  }
}

.sort-btn {
  border-right: 1px solid #ebedf0;
  padding-right: 12px;
}

.message-header {
  margin-bottom: 8px;
}

.message-list {
  background-color: white;
}

.message-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
  transition: background-color 0.2s;

  &:hover {
    background-color: #f8f8f8;
  }

  &:last-child {
    border-bottom: none;
  }
}

.avatar {
  position: relative;
  margin-right: 12px;

  .unread-badge {
    position: absolute;
    top: -5px;
    right: -5px;
  }
}

.message-content {
  flex: 1;
  min-width: 0;

  .message-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 4px;

    .name {
      font-size: 16px;
      font-weight: 500;
      color: #323233;
    }

    .time {
      font-size: 12px;
      color: #969799;
      white-space: nowrap;
    }
  }

  .message-preview {
    font-size: 14px;
    color: #646566;
    line-height: 1.4;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-bottom: 4px;
  }

  .status {
    font-size: 12px;
    color: #1989fa;
  }
}

.arrow {
  color: #c8c9cc;
  font-size: 16px;
  margin-left: 8px;
}

.empty {
  padding: 60px 0;
}

/* 修复导航栏遮挡问题 */
:deep(.van-nav-bar) {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}
</style>
